package com.example.administrator.wallet.view.activity.mine.Help;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.wallet.R;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.FeedBackBean;
import com.example.administrator.wallet.utils.DimbgUtils;
import com.example.administrator.wallet.utils.FileUtils;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.OkHttpFinal;
import cn.finalteam.okhttpfinal.OkHttpFinalConfiguration;
import cn.finalteam.okhttpfinal.RequestParams;
import mvp.presenter.HeaderPresenter;
import mvp.view.IHeaderView;
import okhttp3.Headers;


public class FeedBackActivity extends AppCompatActivity implements IHeaderView {
    private ImageButton bt_back;
    private TextView mV_title;
    private ImageButton mRl_addphoto;
    private View view;
    private  RelativeLayout mRl;
    private HeaderPresenter headerPresenter;
    private String mFilePath;
    private String mContentType = "application/pdf";//打开pdf
    private String mPDFPath;
    private static final int MSG_TAKE_PHOTO = 1;
    private Button mBt_feedback;
    private File file;
    private EditText mEt_feedback;
    private FeedBackBean feedBackBean;
    private int code = 0;
    final IRequestManager reqequestManager = RequestFactory.getReqequestManager();
    private RelativeLayout activity_main;
    private File file_photo;
    private RequestParams params;




    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);

        setStatuColor();
        bt_back = (ImageButton) findViewById(R.id.finish_img);
        mV_title = (TextView) findViewById(R.id.view_title);
        mRl_addphoto = (ImageButton) findViewById(R.id.bt_add);
        mRl = (RelativeLayout) findViewById(R.id.rl_rl);
        mBt_feedback = (Button) findViewById(R.id.bt_feedback);
        mEt_feedback = (EditText) findViewById(R.id.et_feedback);
        activity_main = (RelativeLayout) findViewById(R.id.rl);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        headerPresenter = new HeaderPresenter(this, this);
        FileUtils.init();
        mFilePath = FileUtils.getFileDir() + File.separator;
        mPDFPath = FileUtils.getFileDir() + File.separator + "abc.pdf";

        mRl_addphoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHead();
            }
        });

        mBt_feedback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(mEt_feedback.getText().toString())){
                    Toast.makeText(getApplicationContext(), R.string.Submissioncannotbeempty,Toast.LENGTH_SHORT).show();
                }else{
                    HttpRequest.post(Api.BaseUrl+ Api.Feed_Back,params,new BaseHttpRequestCallback(){
                        @Override
                        protected void onSuccess(Headers headers, Object o) {
                            super.onSuccess(headers, o);
                            Toast.makeText(FeedBackActivity.this, R.string.Submitted, Toast.LENGTH_SHORT).show();
                            onBackPressed();
                        }
                        @Override
                        public void onFailure(int errorCode, String msg) {
                            super.onFailure(errorCode, msg);
                            onBackPressed();

                        }
                    });

                }
            }
        });
        bt_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               onBackPressed();
            }
        });

        bt_back.setVisibility(View.VISIBLE);
        mV_title.setText(R.string.feedback);


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(FeedBackActivity.this,HelpActivity.class));
        finish();
        overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);
    }

    private void initHead() {
        view = View.inflate(this, R.layout.popup_head, null);
        final Button open_camera = (Button) view.findViewById(R.id.open_camera);
        final Button open_photo = (Button) view.findViewById(R.id.open_photo);
        final Button bt_cancel = (Button) view.findViewById(R.id.bt_cancel);

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                final PopupWindow window = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                window.setFocusable(true);
                window.setTouchable(true);
                window.setOutsideTouchable(true);
                window.showAtLocation(activity_main, Gravity.CENTER, 0, 0);
                Log.e("TAG-----", "OK");
                DimbgUtils.dimBackground(FeedBackActivity.this, 0.5f);
                window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        DimbgUtils.dimBackground(FeedBackActivity.this, 1.0f);
                    }
                });

                //相机
                open_camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        headerPresenter.takePhoto();
                        if (Build.VERSION.SDK_INT >= 23) {
                            int checkCallPhonePermission = ContextCompat.checkSelfPermission(FeedBackActivity.this, Manifest.permission.CAMERA);
                            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(FeedBackActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
                                window.dismiss();
                                return;
                            } else {
                                headerPresenter.takePhoto(FeedBackActivity.this);//调用具体方法
                                window.dismiss();

                            }
                        } else {
                            headerPresenter.takePhoto(FeedBackActivity.this);//调用具体方法
                            window.dismiss();

                        }

//                        jump2Camera();
                        window.dismiss();

                    }
                });

                //相册
                open_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        headerPresenter.selectFromAlbum();
                        window.dismiss();
                    }
                });

                bt_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });
            }
        });

    }

    public void setHeaderBitmap(Bitmap bitmap) {
        mRl_addphoto.setImageBitmap(bitmap);
        file_photo = headerPresenter.getFile(bitmap);
        OkHttpFinalConfiguration.Builder builder = new OkHttpFinalConfiguration.Builder();
        OkHttpFinal.getInstance().init(builder.build());
        params = new RequestParams();
        params.addFormDataPart("access_token", SharedPrefsUtil.getValue(FeedBackActivity.this, "wallet", "token", ""));
        params.addFormDataPart("freeText",mEt_feedback.getText().toString());
        params.addFormDataPart("head_portrait",file_photo);
        String path = file_photo.getPath();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 点击取消按钮
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case 2:
                Uri uri = data.getData();
               headerPresenter.startPhoto(uri);
                break;
            case 3:
                file = new File(Environment.getExternalStorageDirectory() + "/" + "iMon.jpg");
                headerPresenter.startPhoto(Uri.fromFile(file));
                break;
            case 4:
                if (data != null) {
                    headerPresenter.setView(data);
                }
                break;
            case MSG_TAKE_PHOTO:
                Log.i("main","to do");
                break;
        }
    }
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            //就像onActivityResult一样这个地方就是判断你是从哪来的。
            case 222:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    headerPresenter.takePhoto(FeedBackActivity.this);
                } else {
                    // Permission Denied
                    Toast.makeText(FeedBackActivity.this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //标题
    public void setStatuColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(android.R.color.white));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setMiuiStatusBarDarkMode(this, true);
        setMiuiStatusBarDarkMode(this, true);
    }
    //设置成白色的背景，字体颜色为黑色。
    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }
}
